﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Input;
using DataLayer;
using System.Windows.Media.Imaging;
using wpf = System.Windows;
using AvalonDock;
namespace LuanVanProject
{

        /// <summary>
        /// This Class Provides the TreeView with extended functionalities like,
        /// Adding the HeaderText feature to Node, Setting the icon for TreeViewNode.
        /// </summary>
        public class TreeViewItemWithIcons : TreeViewItem
        {
            #region Supported Class: TreeViewTag
            public class TreeViewTag
            {
                public Node node;
                public DocumentContent Doc;
            }
            #endregion

            #region static properties
            //ImageSource for item
            static public ImageSource treeIcon;
            static public ImageSource branchIcon;
            static public ImageSource leafIcon;
            static public Image removeIcon;
            static public Image addChildIcon;
            static public Image viewInTabIcon;
            static public Image ImportIcon;
            static public Image renameIcon;
            //Component that interactive with
            static public DetailViewContent DetailView;
            public ProjectPane projectPane;
            static public TreeView NodeTree;
            static public MindMap currentMindmap;
            static public DocumentPane dockPane;
            static private bool isEditing;
            //Drag drop variable
            static Point _lastMouseDown;
            static bool isInsertPress;
            static TreeViewItemWithIcons draggedItem, _target;
            #endregion Global variables

            #region Properties
            //Properties of TreeViewItemwithIcon
            public ImageSource iconSource;
            TextBlock textBlock;

            public TextBlock TextBlock
            {
                get { return textBlock; }
                set { textBlock = value; }
            }
            TextBox tbName;
            Image icon;
            public ImageSource Icon
            {
                set
                {
                    iconSource = value;
                    icon.Source = iconSource;
                }
                get
                {
                    return iconSource;
                }
            }

            /// <summary>
            /// Gets/Sets the HeaderText of TreeViewWithIcons
            /// </summary>
            public string HeaderText
            {
                set
                {
                    textBlock.Text = value;
                    tbName.Text = value;
                }
                get
                {
                    return textBlock.Text;
                }
            }
            #endregion

            #region Static Functions implement for static properties and Supported Fuctions
            static public void PrepareArgument(TreeView tree,MindMap mind,DetailViewContent detail)
            {
                //Interactive component
                DetailView = detail;
                NodeTree = tree;
                currentMindmap = mind;

                //Icon go with each item
                string packUri = "pack://application:,,,/Images/tree.jpg";
                treeIcon = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;
                packUri = "pack://application:,,,/Images/branch.jpg";
                branchIcon = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;
                packUri = "pack://application:,,,/Images/leaves.jpg";
                leafIcon = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;
                
                //Icon of context menu
                addChildIcon = new Image();
                Uri uri1 = new Uri("pack://application:,,,/Images/sq_plus.png");
                BitmapImage sourceAddChildIcon = new BitmapImage(uri1);
                addChildIcon.Source = sourceAddChildIcon;
                addChildIcon.Height = 16;
                addChildIcon.Width = 16;

                viewInTabIcon = new Image();
                Uri uri2 = new Uri("pack://application:,,,/Images/app_window.png");
                BitmapImage sourceViewInTabIcon = new BitmapImage(uri2);
                viewInTabIcon.Source = sourceViewInTabIcon;
                viewInTabIcon.Height = 16;
                viewInTabIcon.Width = 16;

                ImportIcon = new Image();
                Uri uri5 = new Uri("pack://application:,,,/Images/doc_import.png");
                BitmapImage sourceImportIcon = new BitmapImage(uri5);
                ImportIcon.Source = sourceImportIcon;
                ImportIcon.Height = 16;
                ImportIcon.Width = 16;

                removeIcon = new Image();
                Uri uri3 = new Uri("pack://application:,,,/Images/remove.png");
                BitmapImage sourceRemoveIcon = new BitmapImage(uri3);
                removeIcon.Source = sourceRemoveIcon;
                removeIcon.Height = 16;
                removeIcon.Width = 16;

                renameIcon = new Image();
                Uri uri4 = new Uri("pack://application:,,,/Images/text_letter_t.png");
                BitmapImage renameImage = new BitmapImage(uri4);
                renameIcon.Source = renameImage;
                renameIcon.Height = 16;
                renameIcon.Width = 16;

            }
            static TObject FindVisualParent<TObject>(UIElement child) where TObject : UIElement
            {
                if (child == null)
                {
                    return null;
                }

                UIElement parent = VisualTreeHelper.GetParent(child) as UIElement;

                while (parent != null)
                {
                    TObject found = parent as TObject;
                    if (found != null)
                    {
                        return found;
                    }
                    else
                    {
                        parent = VisualTreeHelper.GetParent(parent) as UIElement;
                    }
                }

                return null;
            }
            #endregion
            
            #region Constructors 
            public TreeViewItemWithIcons()
            {
                //prepare header
                StackPanel stack = new StackPanel();
               
                stack.Orientation = Orientation.Horizontal;
                icon = new Image();
                icon.Height = 16;
                icon.Width = 16;
                icon.VerticalAlignment = VerticalAlignment.Center;
                icon.Margin = new Thickness(0, 0, 4, 0);
                icon.Source = iconSource;
                stack.Children.Add(icon);
                this.AllowDrop = true;
                tbName = new TextBox();
                
                tbName.Visibility = Visibility.Collapsed;
                tbName.VerticalAlignment = VerticalAlignment.Center;
                tbName.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(400);
                textBlock = new TextBlock();
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                textBlock.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(400);
                stack.Children.Add(tbName);
                stack.Children.Add(textBlock);
                Header = stack;
                //prepare context menu
                ContextMenu cMenu;
                cMenu = new ContextMenu();
                MenuItem itemAddChild = new MenuItem();
                itemAddChild.Header = "Add Child";
                itemAddChild.Click += new RoutedEventHandler(itemAddChild_Click); 
                itemAddChild.Icon = addChildIcon;
                cMenu.Items.Add(itemAddChild);
                MenuItem itemViewInTab = new MenuItem();
                TreeViewTag itemTag = new TreeViewTag();

                itemViewInTab.Header = "View in Tab";
                itemViewInTab.Click += new RoutedEventHandler(itemViewInTab_Click);
                itemViewInTab.Icon = viewInTabIcon;
                cMenu.Items.Add(itemViewInTab);

               

                cMenu.Tag = this;
                this.ContextMenu = cMenu;
                //Add event
                this.Expanded += new RoutedEventHandler(TreeViewItemWithIcons_Expanded);
                this.Collapsed += new RoutedEventHandler(TreeViewItemWithIcons_Collapsed);
                this.PreviewDrop += new DragEventHandler(TreeViewItemWithIcons_PreviewDrop);
                this.DragOver += new DragEventHandler(TreeViewItemWithIcons_DragOver);
                this.DragLeave += new DragEventHandler(TreeViewItemWithIcons_DragLeave);
                this.Drop += new DragEventHandler(TreeViewItemWithIcons_Drop);
                this.MouseMove += new MouseEventHandler(TreeViewItemWithIcons_MouseMove);
                this.MouseUp += new MouseButtonEventHandler(TreeViewItemWithIcons_Selected);
                this.KeyUp += new KeyEventHandler(TreeViewItemWithIcons_KeyUp);
                stack.MouseEnter += new MouseEventHandler(stack_MouseEnter);
                stack.MouseLeave += new MouseEventHandler(stack_MouseLeave);

            }

            void TreeViewItemWithIcons_PreviewDrop(object sender, DragEventArgs e)
            {
                e.Effects = DragDropEffects.Copy;    
            }

            void stack_MouseLeave(object sender, MouseEventArgs e)
            {
                this.Background = Brushes.White;
            }

            void stack_MouseEnter(object sender, MouseEventArgs e)
            {
                this.Background = Brushes.LightCyan;
            }

          


            public TreeViewItemWithIcons(Node node)
            {
                //prepare header 
                StackPanel stack = new StackPanel();
                stack.Orientation = Orientation.Horizontal;
                Header = stack;
                icon = new Image();
                icon.Height = 16;
                icon.Width = 16;
                icon.VerticalAlignment = VerticalAlignment.Center;
                icon.Margin = new Thickness(0, 0, 4, 0);
                icon.Source = iconSource;
                this.AllowDrop = true;
                tbName = new TextBox();
                tbName.Visibility = Visibility.Hidden;
                tbName.VerticalAlignment = VerticalAlignment.Center;
                tbName.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(400);
                textBlock = new TextBlock();
                textBlock.VerticalAlignment = VerticalAlignment.Center;
                textBlock.FontWeight = System.Windows.FontWeight.FromOpenTypeWeight(400);
                stack.Children.Add(icon);
                stack.Children.Add(textBlock);
                stack.Children.Add(tbName);
                //Set properties
                this.IsExpanded = true;
                this.Icon = treeIcon;
                this.AllowDrop = true;
                this.IsExpanded = node.IsExpanded;
                this.HeaderText = node.Name;
                node.IsExpanded = true;
                TreeViewTag itemTag = new TreeViewTag();
                itemTag.node = node;
                itemTag.Doc = null;
                this.Tag = itemTag;

                //prepare context menu
                ContextMenu cMenu;
                cMenu = new ContextMenu();
                MenuItem itemDelete = new MenuItem();
                itemDelete.Header = "Delete";
                itemDelete.Click += new RoutedEventHandler(itemDelete_Click);      
                itemDelete.Icon = removeIcon;
                cMenu.Items.Add(itemDelete);
                MenuItem itemAddChild = new MenuItem();
                itemAddChild.Header = "Add Child";
                itemAddChild.Click += new RoutedEventHandler(itemAddChild_Click);
                itemAddChild.Icon =addChildIcon;
                cMenu.Items.Add(itemAddChild);
                MenuItem itemViewInTab = new MenuItem();
                itemViewInTab.Header = "View in Tab";
                itemViewInTab.Click += new RoutedEventHandler(itemViewInTab_Click);
                itemViewInTab.Icon =viewInTabIcon;
                cMenu.Items.Add(itemViewInTab);

                MenuItem itemImport = new MenuItem();
                itemImport.Header = "Import to node";
                itemImport.Click += new RoutedEventHandler(itemImport_Click);
                itemImport.Icon = ImportIcon;
                cMenu.Items.Add(itemImport);

                MenuItem itemRename = new MenuItem();
                itemRename.Header = "Rename";
                itemRename.Icon = renameIcon;
                cMenu.Items.Add(itemRename);
                itemRename.Click += new RoutedEventHandler(itemRename_Click);
                cMenu.Tag = this;
                this.ContextMenu = cMenu;
                
                
                //Add event
                this.PreviewDrop += new DragEventHandler(TreeViewItemWithIcons_PreviewDrop);
                this.DragOver += new DragEventHandler(TreeViewItemWithIcons_DragOver);
                this.DragLeave += new DragEventHandler(TreeViewItemWithIcons_DragLeave);
                this.Drop += new DragEventHandler(TreeViewItemWithIcons_Drop);
                this.MouseMove += new MouseEventHandler(TreeViewItemWithIcons_MouseMove);
                this.Expanded += new RoutedEventHandler(TreeViewItemWithIcons_Expanded);
                this.Collapsed += new RoutedEventHandler(TreeViewItemWithIcons_Collapsed);
                this.Selected += new RoutedEventHandler(TreeViewItemWithIcons_Selected);
                this.KeyUp += new KeyEventHandler(TreeViewItemWithIcons_KeyUp);
                this.MouseDoubleClick += new MouseButtonEventHandler(TreeViewItemWithIcons_MouseDoubleClick);
                //this.MouseUp += new MouseButtonEventHandler(TreeViewItemWithIcons_MouseDoubleClick);
                tbName.LostFocus += new RoutedEventHandler(tbName_LostFocus);
                stack.MouseEnter += new MouseEventHandler(stack_MouseEnter);
                stack.MouseLeave += new MouseEventHandler(stack_MouseLeave);
               // this.LostFocus += new RoutedEventHandler(TreeViewItemWithIcons_LostFocus);
            }

            void itemImport_Click(object sender, RoutedEventArgs e)
            {
                System.Windows.Forms.OpenFileDialog openDlg = new System.Windows.Forms.OpenFileDialog();
                openDlg.Multiselect = false;
                openDlg.Filter = "Supported Files(PPT;PPTX)|*.PPTX;*.PPT";
                if (openDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Node node = ((((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons).Tag as TreeViewTag).node;
                    ProcessDlg processDlg = new ProcessDlg(node, openDlg.FileName, currentMindmap);
                    processDlg.ShowDialog();
                }
            }


           

            #endregion Constructor

            #region Event Handling
            void TreeViewItemWithIcons_LostFocus(object sender, RoutedEventArgs e)
            {
                HeaderText = tbName.Text;
                tbName.Visibility = Visibility.Collapsed;
                textBlock.Visibility = Visibility.Visible;
                (this.Tag as TreeViewTag).node.Name = tbName.Text;
                isEditing = false;
                App.Synchronize();
                
            }
            /// <summary>
            /// Resume visibility of textblock
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void tbName_LostFocus(object sender, RoutedEventArgs e)
            {
                if (App.currentMindmap.GetNodeByName(tbName.Text) == null && this.IsSelected==true ||tbName.Text==HeaderText)
                {
                    if (tbName.Text == "")
                    {
                        MessageBox.Show("Please enter an idea");
                        this.tbName.Text = HeaderText;
                        isEditing = true;
                        if (this.IsSelected == true)
                        {
                            tbName.Visibility = Visibility.Visible;
                            textBlock.Visibility = Visibility.Collapsed;
                        }
                        FocusManager.SetFocusedElement(this, this.tbName);
                    }
                    else
                    {
                        HeaderText = tbName.Text;
                        tbName.Visibility = Visibility.Collapsed;
                        textBlock.Visibility = Visibility.Visible;
                        (this.Tag as TreeViewTag).node.Name = tbName.Text;
                        isEditing = false;
                        App.Synchronize();
                    }
                }
                else
                {
                    MessageBox.Show("Please Select others name. This name already exist at :[" + (App.currentMindmap.GetNodeByName(tbName.Text).NodePath()+"]"));
                    this.tbName.Text = this.HeaderText;
                    FocusManager.SetFocusedElement(this, this.tbName);  
                }
                
            }

            /// <summary>
            /// Rename item
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void TreeViewItemWithIcons_MouseDoubleClick(object sender, MouseButtonEventArgs e)
            {
                
            }
            /// <summary>
            /// Key Handler with [Insert] and [Enter] to insert child node and sibling node
            /// </summary>
            void TreeViewItemWithIcons_KeyUp(object sender, KeyEventArgs e)
            {
              
                //Key=Delete delete selected node
                if (e.Key == Key.Delete && this.IsSelected == true && isEditing == false)
                {
                    Node n = ((sender as TreeViewItemWithIcons).Tag as TreeViewTag).node;
                    if (System.Windows.MessageBox.Show("Would you like to delete '" + n.Name + "'", "Merge", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        App.mainMindmapEditor.ViewModel.AddCommandDelete(n);
                        currentMindmap.DelecteNode(n);
                        App.Synchronize();
                    }
                }
                // Key=Insert add Child Node
                if (e.Key == Key.Insert && this.IsSelected == true && isEditing == false)
                {
                    isInsertPress = true;
                    NewTreeNode formnew = new NewTreeNode();
                    formnew.ShowDialog();
                    if (formnew.msg)
                    {
                        Node node = new Node();
                        node.Name = formnew.result;
                        Node parentNode = ((sender as TreeViewItemWithIcons).Tag as TreeViewTag).node;
                        parentNode.AddNode(node);
                        node.ParentNode = parentNode;
                        App.mainMindmapEditor.ViewModel.AddCommandAdd(node);
                        App.Synchronize();
                    }
                }
                // Key=Enter add Sibling Node
                if (e.Key == Key.Enter && (this.IsSelected == true) && isInsertPress == false && isEditing == false && (((sender as TreeViewItemWithIcons).Tag as TreeViewTag).node).ParentNode!=null)
                {
                    NewTreeNode formnew = new NewTreeNode();
                    formnew.ShowDialog();
                    if (formnew.msg)
                    {
                        Node node = new Node();
                        node.Name = formnew.result;
                        Node parentNode = (((sender as TreeViewItemWithIcons).Tag as TreeViewTag).node).ParentNode;
                        parentNode.AddNode(node);
                        App.mainMindmapEditor.ViewModel.AddCommandAdd(node);
                        node.ParentNode = parentNode;
                        node.ParentNode = parentNode;
                        App.Synchronize();
                    }
                }
                else
                {
                    if (isEditing==false && e.Key == Key.Enter && ((sender as TreeViewItemWithIcons).Parent as TreeViewItemWithIcons) == null)
                    {
                        isInsertPress = false;
                        FocusManager.SetFocusedElement(this, this);
                    }
                }
                //Key=F2 rename
                if (e.Key == Key.F2 && this.IsSelected == true)
                {
                    TreeViewItemWithIcons item = sender as TreeViewItemWithIcons;
                    isEditing = true;
                    if (item.IsSelected == true)
                    {
                        tbName.Visibility = Visibility.Visible;
                        textBlock.Visibility = Visibility.Collapsed;
                    }
                    FocusManager.SetFocusedElement(this,this.tbName);  
                }
                if (e.Key == Key.Enter && isEditing==true && this.IsSelected==true)
                {
                    if (App.currentMindmap.GetNodeByName(this.tbName.Text) == null)
                    {
                        if (tbName.Text == "")
                        {
                            MessageBox.Show("Please enter an idea");
                            this.tbName.Text = HeaderText;
                            isEditing = true;
                            if (this.IsSelected == true)
                            {
                                tbName.Visibility = Visibility.Visible;
                                textBlock.Visibility = Visibility.Collapsed;
                            }
                            FocusManager.SetFocusedElement(this, this.tbName);  
                        }
                        else
                        {
                            tbName_LostFocus(null, null);
                            if (this.Parent != null)
                                FocusManager.SetFocusedElement(projectPane._NodeTree, this);
                            this.IsSelected = true;
                        }
                    }
                    else
                    {
                        if (tbName.Text != HeaderText)
                        {
                            MessageBox.Show("Please Select others name. This name already exist at :[" + (App.currentMindmap.GetNodeByName(tbName.Text).NodePath()) + "]");
                            TreeViewItemWithIcons item = sender as TreeViewItemWithIcons;
                            this.tbName.Text = HeaderText;
                            isEditing = true;
                            if (item.IsSelected == true)
                            {
                                tbName.Visibility = Visibility.Visible;
                                textBlock.Visibility = Visibility.Collapsed;
                            }
                            FocusManager.SetFocusedElement(this, this.tbName);
                        }
                    }
                }
               
            }

            void itemRename_Click(object sender, RoutedEventArgs e)
            {
                TreeViewItemWithIcons item=((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons;
                isEditing = true;
                item.tbName.Visibility = Visibility.Visible;
                item.textBlock.Visibility = Visibility.Collapsed;
                FocusManager.SetFocusedElement(projectPane._NodeTree, item.tbName);
                
            }

            /// Change IsExpanded properties of node when Collapse
            /// </summary>
            void TreeViewItemWithIcons_Collapsed(object sender, RoutedEventArgs e)
            {
                Node node = (this.Tag as TreeViewTag).node;
                if (node != null)
                {
                    node.IsExpanded = false;
                }
            }

            /// <summary>
            /// Change IsExpanded properties of node when Expanded
            /// </summary>
            void TreeViewItemWithIcons_Expanded(object sender, RoutedEventArgs e)
            {
                if (this.Tag != null)
                {
                    Node node = (this.Tag as TreeViewTag).node;
                    if (node != null)
                    {
                        node.IsExpanded = true;
                    }
                }
            }
            /// <summary>
            /// MouseUp event with lead to View Content in Detail View
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void TreeViewItemWithIcons_Selected(object sender, RoutedEventArgs e)
            {
                TreeViewItemWithIcons senderItem = sender as TreeViewItemWithIcons;
                if (senderItem.IsSelected == true)
                {
                    if (projectPane.IsGlobal == false)
                        DetailView.SetContain((senderItem.Tag as TreeViewTag).node);
                    else
                        App.GlobalDetailView.SetContain((senderItem.Tag as TreeViewTag).node);
                }
            }
            /// <summary>
            /// Event Handler on UnSelected Event
            /// </summary>
            /// <param name="args">Eventargs</param>
            protected override void OnUnselected(RoutedEventArgs args)
            {
                base.OnUnselected(args);
                icon.Source = iconSource;
            }
            /// <summary>
            /// Event Handler on Selected Event 
            /// </summary>
            /// <param name="args">Eventargs</param>
            protected override void OnSelected(RoutedEventArgs args)
            {
                base.OnSelected(args);
                icon.Source = iconSource;
            }
            #region Drag-Drop Function
            private void TreeView_MouseDown(object sender, MouseButtonEventArgs e)
            {
                if(isEditing==false)
                if (e.ChangedButton == MouseButton.Left)
                {
                    _lastMouseDown = e.GetPosition(NodeTree);
                }
            }
            private void TreeViewItemWithIcons_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
            {
                if(isEditing==false)
                {
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        Point currentPosition = e.GetPosition(NodeTree);


                        if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 10.0) ||
                           (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
                        {
                            draggedItem = (TreeViewItemWithIcons)NodeTree.SelectedItem;
                            if (draggedItem != null)
                            {
                                System.Windows.DragDropEffects finalDropEffect = DragDrop.DoDragDrop(NodeTree, NodeTree.SelectedValue,
                                    System.Windows.DragDropEffects.Move);
                                if ((finalDropEffect == System.Windows.DragDropEffects.Move) && (_target != null))
                                {
                                    if (!draggedItem.HeaderText.Equals(_target.HeaderText))
                                    {
                                       
                                        CopyItem(draggedItem, _target);
                                        App.Synchronize();
                                        _target = null;
                                        draggedItem = null;
                                       
                                    }
                                }
                            }
                        }
                    }
                }
             }
            private void TreeViewItemWithIcons_DragOver(object sender, System.Windows.DragEventArgs e)
            {
                    if(isEditing==false)
                    {
                    (sender as TreeViewItemWithIcons).BorderBrush = Brushes.Aqua;
                    (sender as TreeViewItemWithIcons).BorderThickness = new Thickness(2);
                    Point currentPosition = e.GetPosition(NodeTree);


                    if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 10.0) ||
                        (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 10.0))
                    {
                        // Verify that this is a valid drop and then store the drop target
                        TreeViewItemWithIcons item = GetNearestContainer(e.OriginalSource as UIElement);
                        if (CheckDropTarget(draggedItem, item))
                        {
                            e.Effects = System.Windows.DragDropEffects.Move;
                        }
                        else
                        {
                            e.Effects = System.Windows.DragDropEffects.None;
                        }
                    }
                    if(e.Data.GetDataPresent(System.Windows.DataFormats.Text,true))
                    {
                        e.Effects=System.Windows.DragDropEffects.Move;
                    }
                    e.Handled = true;
                }               
            }
            private void TreeViewItemWithIcons_DragLeave(object sender, System.Windows.DragEventArgs e)
            {
                if(isEditing==false)
                {
                    (sender as TreeViewItemWithIcons).BorderBrush = null;
                    (sender as TreeViewItemWithIcons).BorderThickness = new Thickness(0);
                }


            }
            private void TreeViewItemWithIcons_Drop(object sender, System.Windows.DragEventArgs e)
            {
                try
                {
                    if (isEditing == false)
                    {
                        e.Effects = System.Windows.DragDropEffects.None;
                        e.Handled = true;
                        (sender as TreeViewItemWithIcons).BorderThickness = new Thickness(0);
                        (sender as TreeViewItemWithIcons).BorderBrush = null;
                        // Verify that this is a valid drop and then store the drop target
                        TreeViewItemWithIcons TargetItem = (((e.OriginalSource as UIElement) as TextBlock).Parent as StackPanel).Parent as TreeViewItemWithIcons;
                        if (TargetItem != null && draggedItem != null)
                        {
                            _target = TargetItem;
                            e.Effects = System.Windows.DragDropEffects.Move;
                        }
                        NetworkUI.NetworkView NetworkTarget = e.OriginalSource as NetworkUI.NetworkView;
                        if (NetworkTarget != null)
                        {
                            _target = TargetItem;
                        }
                        //drop from outside
                        if (e.Data.GetDataPresent(System.Windows.DataFormats.Rtf, true))
                        { 
                            //add node here
                            e.Effects = DragDropEffects.Copy;
                            string strData = e.Data.GetData(System.Windows.DataFormats.Rtf, true).ToString();
                            string nodeName = e.Data.GetData(System.Windows.DataFormats.Rtf, true).ToString();
                            System.Windows.Forms.RichTextBox rt = new System.Windows.Forms.RichTextBox();
                            rt.Rtf = nodeName;
                            string nodeNameConverted = rt.Text;
                            if (App.currentMindmap.GetNodeByName(nodeNameConverted.TrimEnd().TrimStart()) == null)
                            {
                                Node node = new Node();
                                node.Name = nodeNameConverted;
                                TreeViewItemWithIcons item = sender as TreeViewItemWithIcons;
                                (item.Tag as TreeViewTag).node.AddNode(node);
                                App.Synchronize();
                            }
                            else
                            {
                                MessageBox.Show("This idea already exist at :[" + (App.currentMindmap.GetNodeByName(tbName.Text).NodePath()) + "]");
                            }
                        }
                    }
                }
                catch { }
            }
            private bool CheckDropTarget(TreeViewItemWithIcons _source, TreeViewItemWithIcons _target)
            {
                try
                {
                    //Check whether the target item is meeting your condition
                    bool _isEqual = false;
                    if (!_source.HeaderText.Equals(_target.HeaderText) && _target != (_source.Parent as TreeViewItemWithIcons))
                    {
                        _isEqual = true;
                    }
                    return _isEqual;
                }
                catch
                {
                    return false;
                }

                
            }
            private void CopyItem(TreeViewItemWithIcons _sourceItem, TreeViewItemWithIcons _targetItem)
            {

                //Asking user wether he want to drop the dragged TreeViewItemWithIcons here or not
                
                if (System.Windows.MessageBox.Show("Would you like to drop '" + _sourceItem.HeaderText + " ' into '" + _targetItem.HeaderText + "'", "Merge", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                        //adding dragged TreeViewItemWithIcons in target TreeViewItem
                        addChild(_sourceItem, _targetItem);
                        //finding Parent TreeViewItem of dragged TreeViewItem 
                        TreeViewItemWithIcons ParentItem = FindVisualParent<TreeViewItemWithIcons>(_sourceItem);
                        // if parent is null then remove from TreeView else remove from Parent TreeViewItem
                        if (ParentItem == null)
                        {
                            NodeTree.Items.Remove(_sourceItem);
                            currentMindmap.RemoveNode((_sourceItem.Tag as TreeViewTag).node.Name);
                            
                        }
                        else
                        {
                            ParentItem.Items.Remove(_sourceItem);
                            ((ParentItem.Tag as TreeViewTag).node).ChildrenNodeList.Remove((_sourceItem.Tag as TreeViewTag).node);
                            if (ParentItem.Items.Count == 0)
                            {
                                ParentItem.Icon = leafIcon;
                            }
                        }
                        App.Synchronize();
                    
                }
            }
            public void addChild(TreeViewItemWithIcons _sourceItem, TreeViewItemWithIcons _targetItem)
            {

                Node sendernode = (_sourceItem.Tag as TreeViewTag).node;
                Node parentNode= _targetItem.Tag as Node;
                ((_targetItem.Tag as TreeViewTag).node).AddNode(sendernode);
                //sendernode.ParentNode = parentNode;
                //App.Synchronize();
            }
            private TreeViewItemWithIcons GetNearestContainer(UIElement element)
            {
                // Walk up the element tree to the nearest tree view item.
                TreeViewItemWithIcons container = element as TreeViewItemWithIcons;
                while ((container == null) && (element != null))
                {
                    element = VisualTreeHelper.GetParent(element) as UIElement;
                    container = element as TreeViewItemWithIcons;
                }
                return container;
            }
            #endregion
            #endregion

            #region MenuContext Commands
            /// <summary>
            /// Command AddChild of context menu
            /// </summary>
            void itemAddChild_Click(object sender, RoutedEventArgs e)
            {
                NewTreeNode formnew = new NewTreeNode();
                formnew.ShowDialog();
                if (formnew.msg)
                {
                    Node node = new Node();
                    node.Name = formnew.result;
                    Node parentNode = ((((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons).Tag as TreeViewTag).node;
                    parentNode.AddNode(node);
                    node.ParentNode = parentNode;
                    App.Synchronize();
                }
            }
            /// <summary>
            /// Command View In Tab of context menu
            /// </summary>
            void itemViewInTab_Click(object sender, RoutedEventArgs e)
            {
                Node node = ((((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons).Tag as TreeViewTag).node;
                MindmapEditor editor = new MindmapEditor();
                DocumentContent itemDock = new DocumentContent();
                itemDock.Title = "[Mindmap] " + node.Name;
                itemDock.Content = editor;
                App.DockPane.Items.Add(itemDock);
                editor.LoadData(node);
                App.observerList.Add(editor);
            }
            /// <summary>
            /// Command Delete of Context Menu
            /// </summary>
            void itemDelete_Click(object sender, RoutedEventArgs e)
            {
                Node n=(( ((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons).Tag as TreeViewTag).node;

                if (System.Windows.MessageBox.Show("Would you like to delete '" + n.Name +"'", "Merge", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    App.mainMindmapEditor.ViewModel.AddCommandDelete(n);
                   
                    TreeViewItemWithIcons item = ((sender as MenuItem).Parent as ContextMenu).Tag as TreeViewItemWithIcons;
                    Node node = (item.Tag as TreeViewTag).node;
                    currentMindmap.DelecteNode(node);
                    if ((item.Parent as TreeViewItemWithIcons) == null)
                    {
                        NodeTree.Items.Remove(item);
                        App.Synchronize();
                    }
                    else
                    {
                        TreeViewItemWithIcons parent = item.Parent as TreeViewItemWithIcons;
                        parent.Items.Remove(item);
                        App.Synchronize();
                    }
                }
            }
            #endregion
        }

}
